package logic

import (
	"context"
	"douban/models/cache"
	"douban/models/mysql"
	"fmt"

	"douban/doubanrpc/doubanrpc"
	"douban/doubanrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *doubanrpc.CartAddRequest) (*doubanrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	if in.Quantity > 100 {
		return nil, fmt.Errorf("库存不足")
	}

	var product mysql.Product

	err := mysql.DB.Debug().Where("id=?", in.ProductId).First(&product).Error

	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if in.Quantity > product.Stock {
		return nil, fmt.Errorf("库存不足")
	}
	err = cache.UpdateCartQuantity(in.UserId, in.ProductId, in.Quantity)

	if cache.CartProduct(in.UserId, in.ProductId) {
		productMap := map[string]interface{}{
			"productId": in.ProductId,
			"userId":    in.UserId,
			"quantity":  in.Quantity,
		}
		err = cache.CartAdd(in.UserId, in.ProductId, productMap)
		if err != nil {
			return nil, fmt.Errorf("购物车添加失败")
		}
	}

	return &doubanrpc.CartAddResponse{
		Success: true,
		Message: "购物车添加成功",
	}, nil
}
